
package me.zhengjie.service.impl;

import lombok.Data;
import me.zhengjie.domain.AppMessage;
import me.zhengjie.domain.AppMessageTo;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.repository.AppMessageToRepository;
import me.zhengjie.service.mapstruct.AppMessage2Mapper;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AppMessageRepository;
import me.zhengjie.service.AppMessageService;
import me.zhengjie.service.dto.AppMessageDto;
import me.zhengjie.service.dto.AppMessageQueryCriteria;
import me.zhengjie.service.mapstruct.AppMessageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author IQW
* @date 2022-07-18
**/
@Service
@RequiredArgsConstructor
public class AppMessageServiceImpl implements AppMessageService {

    private final AppMessageRepository appMessageRepository;
    private final AppMessageToRepository appMessageToRepository;
    private final AppMessageMapper appMessageMapper;
    private final AppMessage2Mapper appMessage2Mapper;

    private final UserService userService;
    private final RoleService roleService;

    @Override
    public Map<String,Object> queryAll(AppMessageQueryCriteria criteria, Pageable pageable){
        Page<AppMessage> page = appMessageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(appMessageMapper::toDto));
    }

    @Override
    public Map<String,Object> queryAllApi(AppMessageQueryCriteria criteria, Pageable pageable){
        Integer userId = SecurityUtils.getCurrentUserId().intValue();
        criteria.setUids(","+userId+",");
        Page<AppMessage> page = appMessageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        page.getContent().forEach(appMessage -> {
            //查询状态
            AppMessageTo tmp = appMessageToRepository.queryByUserIdAndMsgId(userId,appMessage.getMsgId());
            if(null != tmp && tmp.getStatus() == 1){
                appMessage.setStatus(1);
            }else{
                appMessage.setStatus(0);
            }
        });
        return PageUtil.toPages(page.map(appMessage2Mapper::toDto),"");
    }

    @Override
    public List<AppMessageDto> queryAll(AppMessageQueryCriteria criteria){

        //获取最小权限
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        System.out.println("min level:"+currentLevel);
        if(currentLevel<=2){
            //管理员查看所有
        }else{
            //查询自己发布的
            Long userId = SecurityUtils.getCurrentUserId();
//            UserDto user = userService.findById(userId);
            criteria.setUserId(userId.intValue());
//            criteria.setAreaId(user.getAreaId());
        }

        return appMessageMapper.toDto(appMessageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AppMessageDto findById(Integer msgId) {
        AppMessage appMessage = appMessageRepository.findById(msgId).orElseGet(AppMessage::new);
        ValidationUtil.isNull(appMessage.getMsgId(),"AppMessage","msgId",msgId);
        return appMessageMapper.toDto(appMessage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppMessageDto create(AppMessage resources) {

        if(StringUtils.isEmpty(resources.getToType()) || StringUtils.isEmpty(resources.getToAreaId())){
            throw new BadRequestException("参数错误");
        }

        //查询用户在哪个责任区
        UserDto user = userService.findById(SecurityUtils.getCurrentUserId());
        resources.setUserId(user.getId().intValue());
        resources.setAreaId(user.getAreaId());
        resources.setStatus(0);
        resources.setCreateTime(DateUtils.getNowTimestamp());


        //查询用户，添加到messageTo表
        String selUids = "0";
        if(!StringUtils.isEmpty(resources.getUids())){
            selUids = resources.getUids();
        }
        List<AppMessageTo> insert = new LinkedList<>();
        String uids = "0,";
        //to_type 1全部，2林长，3护林员，4个人
        List<User> users = userService.findByAreaIdAndLzzw(resources.getToAreaId(),resources.getToType(),selUids);
        for (User item :users){
            AppMessageTo msgTo = new AppMessageTo();
            msgTo.setUserId(item.getId().intValue());
            msgTo.setNickName(item.getNickName());
            msgTo.setStatus(0);
            msgTo.setCreateTime(DateUtils.getNowTimestamp());

            insert.add(msgTo);
            uids += item.getId()+",";
        }
        uids += "0";    //故意在前后+0

        resources.setUids(uids);
        resources.setNum(users.size());
        AppMessage msg = appMessageRepository.save(resources);

        //批量插入msgTo
        for (AppMessageTo msgTo :insert){
            msgTo.setMsgId(msg.getMsgId());
            appMessageToRepository.save(msgTo);
        }

        return appMessageMapper.toDto(msg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppMessage resources) {
        AppMessage appMessage = appMessageRepository.findById(resources.getMsgId()).orElseGet(AppMessage::new);
        ValidationUtil.isNull( appMessage.getMsgId(),"AppMessage","id",resources.getMsgId());
        appMessage.copy(resources);
        appMessageRepository.save(appMessage);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer msgId : ids) {
            appMessageRepository.deleteById(msgId);
        }
    }

    @Override
    public void download(List<AppMessageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppMessageDto appMessage : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("责任区ID", appMessage.getAreaId());
            map.put("标题", appMessage.getTitle());
            map.put("消息类型", appMessage.getType());
            map.put("内容", appMessage.getContent());
            map.put("巡护频次", appMessage.getNum());
            map.put("对象责任区ID", appMessage.getToAreaId());
            map.put("对角类型", appMessage.getToType());
            map.put("选择人员ID", appMessage.getUids());
            map.put("状态", appMessage.getStatus());
            map.put(" createTime",  appMessage.getCreateTime());
            map.put(" updateTime",  appMessage.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}